package com.augurit.gzcgwsp.smartformCsdlwj.service.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.util.lang.DateUtils;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.common.util.CommonUtils;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.sendNotice.service.IExchangeStateService;
import com.augurit.gzcgwsp.sendNotice.service.IYwMtbjlshInfoService;
import com.augurit.gzcgwsp.sendNotice.service.IYwWebserviceForWbService;
import com.augurit.gzcgwsp.sendNotice.service.IYwWebserviceInfoService;
import com.augurit.gzcgwsp.smartformCsdlwj.convert.YwSrGgcsConvertor;
import com.augurit.gzcgwsp.smartformCsdlwj.dao.YwSSGgcsDao;
import com.augurit.gzcgwsp.smartformCsdlwj.entity.YwGgcs;
import com.augurit.gzcgwsp.smartformCsdlwj.entity.YwSrCsdlwj;
import com.augurit.gzcgwsp.smartformCsdlwj.service.IYwGgcsServices;
import com.augurit.gzcgwsp.smartformCsdlwj.web.form.GgcsForm;
import com.augurit.gzcgwsp.smartformCsdlwj.web.form.ShljqsForm;
import com.augurit.gzcgwsp.ssgd.web.form.YwRqSsgdSqbForm;
import com.augurit.gzcgwsp.wfex.common.service.IWfServiceEX;
import com.augurit.gzcgwsp.ywcmn.service.IYwComQyxxService;
import com.augurit.gzcgwsp.ywcmn.service.IYwComSjclService;
import com.augurit.gzcgwsp.ywcmn.service.IYwComSjcllistService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComQyxxForm;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComSjclForm;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComSjcllistForm;
import com.augurit.wf.app.doccode.service.IOaDocCodeService;
import com.augurit.wf.app.doccode.web.form.OaDocCodeForm;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.common.service.impl.WfBusClientServiceImpl;

/**
 * 公共厕所审批
 * @author Administrator
 *
 */
@Service
@Transactional
public class YwGgcsServicesImpl extends WfBusClientServiceImpl<GgcsForm> implements IYwGgcsServices{
	
	@Autowired
	private YwSSGgcsDao ywSSGgcsDao;	
	@Autowired
	private IYwComQyxxService ywComQyxxService;
	@Autowired
	private IYwComSjcllistService ywComSjcllistService;
	@Autowired
	private IYwComSjclService ywComSjclService;
	@Autowired
    private IYwMtbjlshInfoService ywMtbjlshInfoService;
	@Autowired
    private IYwComSjclService sjclService;
    @Autowired
	private IYwWebserviceInfoService ywWebserviceInfoService;
    @Autowired
    private IYwWebserviceForWbService ywWebserviceForWbService;
    @Autowired
    private IExchangeStateService exchangeStateService;
    @Autowired
    private IWfServiceEX wfServiceEX;
	 
	public List<YwGgcs> getByAcceptNo(String acceptNo)
	 {
		 List<YwGgcs> entityList=null;
		 String sql = "from YwGgcs t where t.acceptNo='" + acceptNo + "'";
		 try {
			  entityList = ywSSGgcsDao.find(sql);
		} catch (Exception e) {
			String a=e.toString();
		}
	      
	       return entityList;
	 }
	
	public Page<GgcsForm> search(Page<GgcsForm> page, GgcsForm form) {
		// TODO Auto-generated method stub
		return null;
	}
	public Page<GgcsForm> search(Page<GgcsForm> page,
			List<PropertyFilter> filters) {
		// TODO Auto-generated method stub
		return null;
	}
	public void save(GgcsForm form) {

		System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"+form.getGcmc());
		
        if (form == null) return;

        YwGgcs entity = new YwGgcs(); 
        if(form != null && form.getId() != null){
            entity = ywSSGgcsDao.get(form.getId());
            if (StringUtils.isBlank(entity.getAcceptNo()) || form.getAcceptNo().indexOf("XXXX") > 0) form.setAcceptNo(null);
        }else{
            entity = new YwGgcs(); 
            form.setAcceptNo(null);
        }
        
        //保存企业信息
        YwComQyxxForm qyxxForm = new YwComQyxxForm();
        if(StringUtils.isEmpty(form.getQybh())){
        	if(StringUtils.isNotBlank(form.getSqdw())){
            	YwComQyxxForm ywComQyxxForm = ywComQyxxService.getFormBySqdw(form.getSqdw(), "ccgbggcs");
            	if(ywComQyxxForm != null){
            		qyxxForm = ywComQyxxForm;
            	}
            }
        }
        YwSrGgcsConvertor.convertFormToQyxxForm(form, qyxxForm);
        qyxxForm.setTemplateCode("ccgbggcs");
        ywComQyxxService.update(qyxxForm);
        form.setQybh(qyxxForm.getId().toString());
        System.out.println("&&&&&&&&&&&&&&&&&&&&&  qyxxForm =  "+qyxxForm.getId());
        
        boolean isNewForm = false;
        if (StringUtils.isBlank(form.getAcceptNo())) {
        	//生成政务中心统一查询编号 开始
			Map<String,String> serialNoAndPasswordMap = null;
        	if("Y".equals(form.getSendNotice())){//网办，1
        		serialNoAndPasswordMap = ywMtbjlshInfoService.getSerialNoAndPassword("1");
        	}else{//大厅，0
        		serialNoAndPasswordMap = ywMtbjlshInfoService.getSerialNoAndPassword("0");
        	}
        	String serialNo = serialNoAndPasswordMap.get("serialNo");
        	String password = serialNoAndPasswordMap.get("password");
			form.setSerialNo(serialNo);
			form.setPassword(password);
			form.setAcceptNo(serialNo);
    		//生成政务中心统一查询编号 结束
            isNewForm = true;
        }
        YwSrGgcsConvertor.convertFormToVo(form, entity); 
        System.out.println("&&&&&&&&&&&&&&&&&&&&&  后  "+entity.getSqdw());
        System.out.println("&&&&&&&&&&&&&&&&&&&&&  entity.getId() =  "+entity.getId());
        Session session = ywSSGgcsDao.getSessionFactory().openSession();
        session.save(entity);
        session.flush();
        session.close();
        form.setId(entity.getId());
        
        if (isNewForm) {
            sjclService.updateByNewForm(form.getId());
        }
	}
	public void delete(Long... ids) {
		// TODO Auto-generated method stub
		
	}
	public GgcsForm get(Long id) {
		YwGgcs entity = ywSSGgcsDao.get(id);
		GgcsForm form = YwSrGgcsConvertor.convertVoToForm(entity);
        return form;
	}
	public void save(GgcsForm... forms) {
		if(forms != null)
			for(GgcsForm form : forms)
				this.save(form);
	}
     
	/**
	 * 根据ID获得对象实体
	 * @param id
	 * @return
	 */  
	public YwGgcs getEntity(Long id){
		return ywSSGgcsDao.get(id);
	}
	
	/**
     * 保存对象实体
     * @param ywGgcs
     */     
    public void saveEntity(YwGgcs ywGgcs){
    	ywSSGgcsDao.save(ywGgcs);
    }
    
  //保存结案时间
	public void endSave(Long id) {
		YwGgcs entity = ywSSGgcsDao.get(id);
    	entity.setJarq(new Date());
    	ywSSGgcsDao.save(entity);
	}
	
	public void changeYslState(Long id,Long state,String yslThyy) {
    	StringBuffer sql = new StringBuffer();
    	sql.append("update YwGgcs t set t.ysl="+state);
    	if(StringUtils.isNotBlank(yslThyy)){
    		sql.append(" ,t.yslThyy='"+yslThyy+"'");
    	}
    	sql.append(" where t.id="+id);
    	ywSSGgcsDao.getSession().createQuery(sql.toString()).executeUpdate();
    	System.out.println("公厕收件");
    }
	
	/**
	 * 获取收件通知书里面的材料列表
	 * @param form
	 * @return
	 */
	public GgcsForm getSjtzsField(GgcsForm form){
		form.setSerialNo2(form.getSerialNo());
		form.setPassword2(form.getPassword());
		form.setAcceptNo2(form.getAcceptNo());
		form.setSajg("广州市城市管理委员会");
		form.setSajg2(form.getSajg());
		form.setSajg3(form.getSajg());
		form.setSajg4(form.getSajg());
		form.setCurDate2(DateUtils.dateTimeToString(new Date(),DateUtils.YEAR_MOUTH_DAY_));
		form.setCurDate3(form.getCurDate2());
		form.setCbyw2(form.getCbyw());
		form.setCbyw3(form.getCbyw());
		form.setCbyw4(form.getCbyw());
		form.setSqrq2(form.getSqrq());
		form.setSjr2(form.getSjr());
		form.setYwlxr(form.getSqdw());
		form.setLxr2(form.getSqdw());
		form.setSqdw2(form.getSqdw());
		Long id = form.getId();
		YwComSjcllistForm sjclListForm=new YwComSjcllistForm();
		sjclListForm.setAjid(id);
		sjclListForm.setTplcode("ccgbggcs");
        List<YwComSjcllistForm> sjclList = ywComSjcllistService.getList(sjclListForm);
        YwComSjclForm fkForm = new YwComSjclForm();
//        fkForm.setFkid(form.getQyid());
        fkForm.setAjid(id);
        fkForm.setTplcode("ccgbggcs");
        List<YwComSjclForm> sjclTpl = ywComSjclService.getList(fkForm);
        for (YwComSjcllistForm listForm : sjclList) {
            boolean hasExists = false;
            for (YwComSjclForm tplForm : sjclTpl) {
                if (tplForm.getTplid() != null && listForm.getId().longValue() == tplForm.getTplid().longValue()) {
                    if (StringUtils.isNotBlank(tplForm.getFilepath())) {
                        listForm.setState("1");
                        listForm.setHasfile("1");
                        listForm.setFilename(tplForm.getFilename());
                        listForm.setFilepath(tplForm.getFilepath());
                        listForm.setFiletype(tplForm.getFiletype());
                    } else {
                        listForm.setState("0");
                        listForm.setHasfile("0");
                    }
                    if (tplForm.getYjs() != null) {
                        listForm.setYjs(Long.valueOf(tplForm.getYjs()));
                    }
                    if (tplForm.getFyjs() != null) {
                        listForm.setFyjs(Long.valueOf(tplForm.getFyjs()));
                    }
                    listForm.setClid(tplForm.getId());
                    if ("1".equals(listForm.getSfdz())) {
                        listForm.setDisabled("1");
                    } else {
                        listForm.setDisabled("0");
                        if (tplForm.getSfdz() == null) {
                            listForm.setSfdz("0");
                        } else {
                            listForm.setSfdz(tplForm.getSfdz());
                        }
                    }
                    hasExists = true;
                }
            }
            if (!hasExists) {
                listForm.setState("0");
                listForm.setHasfile("0");
                if ("1".equals(listForm.getSfdz())) {
                    listForm.setDisabled("1");
                } else {
                    listForm.setDisabled("0");
                }
            }
        }
        if(sjclList.size()>0)
		{
				YwComSjcllistForm sjclForm01=sjclList.get(0);
				form.setTitleRow101(sjclForm01.getTitle());
				form.setTitleRow102(sjclForm01.getTitle());
				form.setFyjsRow101(sjclForm01.getFyjs());
				form.setFyjsRow102(sjclForm01.getFyjs());
				form.setFsRow101(sjclForm01.getYjs()+sjclForm01.getFyjs());
				form.setFsRow102(sjclForm01.getYjs()+sjclForm01.getFyjs());
				if("0".equals(sjclForm01.getSfdz()))
				{
					form.setSfdzRow101("√");
					form.setSfdzRow102("√");
				}else{
					form.setSfdzRow101("√");
					form.setSfdzRow102("√");
				}
				
				YwComSjcllistForm sjclForm02=sjclList.get(1);
				form.setTitleRow201(sjclForm02.getTitle());
				form.setTitleRow202(sjclForm02.getTitle());
				form.setFyjsRow201(sjclForm02.getFyjs());
				form.setFyjsRow202(sjclForm02.getFyjs());
				form.setFsRow201(sjclForm02.getYjs()+sjclForm02.getFyjs());
				form.setFsRow202(sjclForm02.getYjs()+sjclForm02.getFyjs());
				if("0".equals(sjclForm02.getSfdz()))
				{
					form.setSfdzRow201("√");
					form.setSfdzRow202("√");
				}else{
					form.setSfdzRow201("√");
					form.setSfdzRow202("√");
				}
				
				
				YwComSjcllistForm sjclForm03=sjclList.get(2);
				form.setTitleRow301(sjclForm03.getTitle());
				form.setTitleRow302(sjclForm03.getTitle());
				form.setFyjsRow301(sjclForm03.getFyjs());
				form.setFyjsRow302(sjclForm03.getFyjs());
				form.setFsRow301(sjclForm03.getYjs()+sjclForm03.getFyjs());
				form.setFsRow302(sjclForm03.getYjs()+sjclForm03.getFyjs());
				if("0".equals(sjclForm03.getSfdz()))
				{
					form.setSfdzRow301("√");
					form.setSfdzRow302("√");
				}else{
					form.setSfdzRow301("√");
					form.setSfdzRow302("√");
				}
				
				YwComSjcllistForm sjclForm04=sjclList.get(3);
				form.setTitleRow401(sjclForm04.getTitle());
				form.setTitleRow402(sjclForm04.getTitle());
				form.setFyjsRow401(sjclForm04.getFyjs());
				form.setFyjsRow402(sjclForm04.getFyjs());
				form.setFsRow401(sjclForm04.getYjs()+sjclForm04.getFyjs());
				form.setFsRow402(sjclForm04.getYjs()+sjclForm04.getFyjs());
				if("0".equals(sjclForm04.getSfdz()))
				{
					form.setSfdzRow401("√");
					form.setSfdzRow402("√");
				}else{
					form.setSfdzRow401("√");
					form.setSfdzRow402("√");
				}
				
				
				YwComSjcllistForm sjclForm05=sjclList.get(4);
				form.setTitleRow501(sjclForm05.getTitle());
				form.setTitleRow502(sjclForm05.getTitle());
				form.setFyjsRow501(sjclForm05.getFyjs());
				form.setFyjsRow502(sjclForm05.getFyjs());
				form.setFsRow501(sjclForm05.getYjs()+sjclForm05.getFyjs());
				form.setFsRow502(sjclForm05.getYjs()+sjclForm05.getFyjs());
				if("0".equals(sjclForm05.getSfdz()))
				{
					form.setSfdzRow501("√");
					form.setSfdzRow502("√");
				}else{
					form.setSfdzRow501("√");
					form.setSfdzRow502("√");
				}
				
				YwComSjcllistForm sjclForm06=sjclList.get(5);
				form.setTitleRow601(sjclForm06.getTitle());
				form.setTitleRow602(sjclForm06.getTitle());
				form.setFyjsRow601(sjclForm06.getFyjs());
				form.setFyjsRow602(sjclForm06.getFyjs());
				form.setFsRow601(sjclForm06.getYjs()+sjclForm06.getFyjs());
				form.setFsRow602(sjclForm06.getYjs()+sjclForm06.getFyjs());
				if("0".equals(sjclForm06.getSfdz()))
				{
					form.setSfdzRow601("√");
					form.setSfdzRow602("√");
				}else{
					form.setSfdzRow601("√");
					form.setSfdzRow602("√");
				}
				
				YwComSjcllistForm sjclForm07=sjclList.get(6);
				form.setTitleRow701(sjclForm07.getTitle());
				form.setTitleRow702(sjclForm07.getTitle());
				form.setFyjsRow701(sjclForm07.getFyjs());
				form.setFyjsRow702(sjclForm07.getFyjs());
				form.setFsRow701(sjclForm07.getYjs()+sjclForm07.getFyjs());
				form.setFsRow702(sjclForm07.getYjs()+sjclForm07.getFyjs());
				if("0".equals(sjclForm07.getSfdz()))
				{
					form.setSfdzRow701("√");
					form.setSfdzRow702("√");
				}else{
					form.setSfdzRow701("√");
					form.setSfdzRow702("√");
				}
				
				YwComSjcllistForm sjclForm08=sjclList.get(7);
				form.setTitleRow801(sjclForm08.getTitle());
				form.setTitleRow802(sjclForm08.getTitle());
				form.setFyjsRow801(sjclForm08.getFyjs());
				form.setFyjsRow802(sjclForm08.getFyjs());
				form.setFsRow801(sjclForm08.getYjs()+sjclForm08.getFyjs());
				form.setFsRow802(sjclForm08.getYjs()+sjclForm08.getFyjs());
				if("0".equals(sjclForm08.getSfdz()))
				{
					form.setSfdzRow801("√");
					form.setSfdzRow802("√");
				}else{
					form.setSfdzRow801("√");
					form.setSfdzRow802("√");
				}
				
				YwComSjcllistForm sjclForm09=sjclList.get(8);
				form.setTitleRow901(sjclForm09.getTitle());
				form.setTitleRow902(sjclForm09.getTitle());
				form.setFyjsRow901(sjclForm09.getFyjs());
				form.setFyjsRow902(sjclForm09.getFyjs());
				form.setFsRow901(sjclForm09.getYjs()+sjclForm09.getFyjs());
				form.setFsRow902(sjclForm09.getYjs()+sjclForm09.getFyjs());
				if("0".equals(sjclForm09.getSfdz()))
				{
					form.setSfdzRow901("√");
					form.setSfdzRow902("√");
				}else{
					form.setSfdzRow901("√");
					form.setSfdzRow902("√");
				}
		}
        
        
		return form;
	}
	
	/**
     * 保存政务中心的统一查询编号和密码
     * @param id
     * @param serialNo
     * @param password
     */
    public void saveSerialNoAndPassword(Long id,String serialNo,String password) {
    	YwGgcs entity = ywSSGgcsDao.get(id);
    	entity.setSerialNo(serialNo);
    	entity.setPassword(password);
    	ywSSGgcsDao.save(entity);
    }

    /*
     * (non-Javadoc)
     * @see com.augurit.gzcgwsp.smartformCsdlwj.service.IYwGgcsServices#saveOherInfo(java.util.Map)
     */
	@Override
	public void saveOherInfo(Map map) {
		String id=(String) map.get("id");
		String bjgzfcr=(String) map.get("bjgzfcr");
		String bjgzyy=(String) map.get("bjgzyy");
		String bjgzsj=(String) map.get("bjgzsj");
		String bjgzqd=(String) map.get("bjgzqd");
		String bjslsj=(String) map.get("bjslsj");
		String sldwcbrxm=(String) map.get("sldwcbrxm");
		String bjclqd=(String) map.get("bjclqd");
		String bjsljtdd=(String) map.get("bjsljtdd");
		String yqts=(String) map.get("yqts");
		if(StringUtils.isNotBlank(id)){
			YwGgcs entity = ywSSGgcsDao.get(Long.valueOf(id));
			
			if(StringUtils.isNotBlank(bjgzsj)){
				Date bjgzdate;
				try {
					bjgzdate = DateUtilsEX.dateFormate(bjgzsj, "yyyy年MM月dd日");
					entity.setBjgzsj(bjgzdate);//补交告知时间
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if(StringUtils.isNotBlank(bjslsj)){
				Date bjslsjdate;
				try {
					bjslsjdate = DateUtilsEX.dateFormate(bjslsj, "yyyy年MM月dd日");
					entity.setBjslsj(bjslsjdate);//补交受理时间
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if(StringUtils.isNotBlank(bjgzfcr)){
				entity.setBjgzfcr(bjgzfcr);//补交告知发出人
			}
			if(StringUtils.isNotBlank(bjgzyy)){
				entity.setBjgzyy(bjgzyy);//补交告知发出人
			}
			if(StringUtils.isNotBlank(bjgzqd)){
				entity.setBjgzqd(bjgzqd);//补交告知发出人
			}
			if(StringUtils.isNotBlank(sldwcbrxm)){
				entity.setSldwcbrxm(sldwcbrxm);//补交告知发出人
			}
			if(StringUtils.isNotBlank(bjclqd)){
				entity.setBjclqd(bjclqd);//补交告知发出人
			}
			if(StringUtils.isNotBlank(bjsljtdd)){
				entity.setBjsljtdd(bjsljtdd);//补交告知发出人
			}
			if(StringUtils.isNotBlank(yqts)){
				entity.setYqts(yqts);//延期天数
			}
			
			this.ywSSGgcsDao.save(entity);
		}
	}

	/*
	 * 修改答复时间
	 * @see com.augurit.gzcgwsp.smartformCsdlwj.service.IYwGgcsServices#updateDfsj(com.augurit.gzcgwsp.smartformCsdlwj.web.form.GgcsForm)
	 */
	@Override
	public void updateDfsj(GgcsForm form) {
		String sql=" update SS_CCGBSQB_V1 set dfsj='"+form.getDfsj()+"' where id="+form.getId();
		this.ywSSGgcsDao.updateDateBase(sql);
		
	}

	public String wfBusYslTuih(GgcsForm form,LoginUserForm loginUser) throws Exception {
    	String  loginUserName = loginUser.getUser().getUserName();
    	WfBusInstanceTaskForm taskForm = new WfBusInstanceTaskForm();
		taskForm.setHandleComments("资料不全，不予受理。");
		//把审批状态数据保存到ywWebserviceInfo ，交换给方欣
		ywWebserviceInfoService.saveYwWebserviceInfo(form.getSqrq(), form.getAcceptNo(), form.getCbyw(), form.getYwlxr(), form.getSjr(), form.getSqdw(), 
				form.getBusinessCode(), form.getApprovalNo(), loginUserName, loginUser.getOrg().getOrgName(), "ysl", new Date(), false, "预受理", taskForm);
//		System.out.println("form.getYslThyy() = "+java.net.URLDecoder.decode(form.getYslThyy(),"UTF-8"));
		this.changeYslState(form.getId(), 0L,taskForm.getHandleComments());
		
		//（网办）交换到市民网页
		Map map=exchangeStateService.buildMap(loginUser, null, form.getId().toString(), form.getTemplateCode(), false);
		String durationExpression = wfServiceEX.getDurationExpressionByTemplateCode(form.getTemplateCode());
		ywWebserviceForWbService.setValueAndSaveYwWebserviceForWb(loginUserName,form.getTemplateCode(),
				form.getId().toString(),durationExpression,"001",taskForm.getHandleComments(), map);
    	return null;
    }

	@Override
	public void updateAcceptNo(YwGgcs form) {
		String hql = "update YwGgcs gd set gd.acceptNo='"+form.getAcceptNo()+"',gd.serialNo='"+form.getAcceptNo()+"' where gd.id=:id";
		Query query =this.ywSSGgcsDao.getSession().createQuery(hql);
		query.setLong("id", form.getId());
		query.executeUpdate();
	}
}
